﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GoShopping.Web.ProductManager
{
    public partial class AddProducts : System.Web.UI.Page
    {
        BLL.ProductBean pb = new GoShopping.BLL.ProductBean();
        protected void Page_Load(object sender, EventArgs e)
        {
            #region Initial
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["ProductID"]))
                {
                    string imgSrc = "~" + GetWebPath(GoShopping.BLL.ProductImgBean.GetProductImgPath(Convert.ToInt32(Request.QueryString["ProductID"]), new BLL.ProductBean().GetProduct(Convert.ToInt32(Request.QueryString["ProductID"])).ProductTypeID)).Substring(1, GetWebPath(GoShopping.BLL.ProductImgBean.GetProductImgPath(Convert.ToInt32(Request.QueryString["ProductID"]), new BLL.ProductBean().GetProduct(Convert.ToInt32(Request.QueryString["ProductID"])).ProductTypeID)).Length - 1);
                    imgPrdt.ImageUrl = imgSrc;
                    BindProductInfo(Request.QueryString["ProductID"]);
                    btnAddBasic.Visible = false;
                    ddlType.Enabled = false;
                    btnEditPrdtBasic.Visible = true;

                    btnAddDetail.Visible = false;
                    btnEditPrdtDetail.Visible = true;
                    return;
                }
                else
                {
                    //dv.Visible = false;
                    btnAddBasic.Visible = true;
                    btnEditPrdtBasic.Visible = false;
                    btnAddDetail.Visible = true;
                    btnEditPrdtDetail.Visible = false;

                    SetDDLType();
                    SetDDLTag();
                    SetDDLBrand();
                    SetDDLSupplier();
                    rdbtnNo.Checked = true;
                }
            }
            CreatePrdtDetailTable(ddlType);
            #endregion
        }

        string GetWebPath(string path)
        {
            return GoShopping.Utility.WebPath.ConvertSpecifiedPathToRelativePath(this, path).Replace("~", ".");
        }

        #region DropDownList DataBind
        private void SetDDLSupplier()
        {
            ddlSupplier.Items.Clear();
            ddlSupplier.DataTextField = "Name";
            ddlSupplier.DataValueField = "ID";
            ddlSupplier.DataSource = new BLL.ProductSuplyBean().GetAllProductSuplyList();
            ddlSupplier.DataBind();
        }

        private void SetDDLBrand()
        {
            ddlBrand.Items.Clear();
            ddlBrand.Items.Add(new ListItem("--请选择--"));
            IList<Model.DicBrand> il = new BLL.DicBrandBean().GetAllBrand();
            foreach (Model.DicBrand db in il)
            {
                ListItem li1 = new ListItem(db.Name);
                ddlBrand.Items.Add(li1);
            }
        }

        private void SetDDLTag()
        {
            ddlTag.Items.Clear();
            ddlTag.Items.Add(new ListItem("--请选择--"));
            IList<Model.DicTag> il = new BLL.SysInfo.DicTagBean().GetAllTag();
            foreach (Model.DicTag dt in il)
            {
                ListItem li1 = new ListItem(dt.Name);
                ddlTag.Items.Add(li1);
            }
        }

        private void SetDDLType()
        {
            SetControlCommon.GetDDLType(ddlType);
        }

        #region Below are for Edit
        private void SetDDLSupplier(int supplyerID)
        {
            ddlSupplier.Items.Clear();
            GoShopping.BLL.ProductSuplyBean psb = new GoShopping.BLL.ProductSuplyBean();
            ddlSupplier.DataTextField = "Name";
            ddlSupplier.DataValueField = "ID";
            foreach (GoShopping.Model.PrdctSupplyer ps in psb.GetAllProductSuplyList())
            {
                ListItem li = new ListItem(ps.Name, ps.ID.ToString());
                ddlSupplier.Items.Add(li);
            }
            ListItem li1 = ddlSupplier.Items.FindByValue(supplyerID.ToString());
            int index = ddlSupplier.Items.IndexOf(li1);
            ddlSupplier.SelectedIndex = index;
        }

        //private void SetDDLPriority(string priority)
        //{
        //    ddlPriority.Items.Clear();
        //    for (int i = 0; i < 10; i++)
        //    {
        //        ddlPriority.Items.Add(i.ToString());
        //    }
        //    ListItem li = ddlSupplier.Items.FindByText(priority);
        //    int index = ddlSupplier.Items.IndexOf(li);
        //    ddlSupplier.SelectedIndex = index;
        //}

        private void SetDDLBrand(string brand)
        {
            ddlBrand.Items.Clear();
            GoShopping.BLL.DicBrandBean dbb = new GoShopping.BLL.DicBrandBean();
            ddlBrand.DataTextField = "Name";
            ddlBrand.DataValueField = "ID";
            foreach (GoShopping.Model.DicBrand db in dbb.GetAllBrand())
            {
                ListItem li = new ListItem(db.Name, db.ID.ToString());
                ddlBrand.Items.Add(li);
            }
            ListItem li1 = ddlBrand.Items.FindByText(brand);
            int index = ddlBrand.Items.IndexOf(li1);
            ddlBrand.SelectedIndex = index;
        }

        private void SetDDLTag(string tag)
        {
            ddlTag.Items.Clear();
            GoShopping.BLL.SysInfo.DicTagBean dtb = new GoShopping.BLL.SysInfo.DicTagBean();
            ddlTag.DataTextField = "Name";
            ddlTag.DataValueField = "ID";
            foreach (GoShopping.Model.DicTag dt in dtb.GetAllTag())
            {
                ListItem li = new ListItem(dt.Name, dt.ID.ToString());
                ddlTag.Items.Add(li);
            }
            ListItem li1 = ddlTag.Items.FindByText(tag);
            int index = ddlTag.Items.IndexOf(li1);
            ddlTag.SelectedIndex = index;
        }

        private void SetDDLType(string typeID)
        {
            SetControlCommon.GetDDLType(ddlType, typeID);
        }
        #endregion
        #endregion

        #region Button Click Event
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            IList<FileUpload> fuList = new List<FileUpload>();
            fuList.Add(FileUpload1);
            fuList.Add(FileUpload2);
            fuList.Add(FileUpload3);
            fuList.Add(FileUpload4);
            fuList.Add(FileUpload5);
            fuList.Add(FileUpload6);
            fuList.Add(FileUpload7);
            fuList.Add(FileUpload8);
            fuList.Add(FileUpload9);
            fuList.Add(FileUpload10);
            GoShopping.BLL.ProductImgBean.SetProductImage(Convert.ToInt32(hidPrdt.Value), Convert.ToInt32(hidPrdtType.Value), fuList);
            //GoShopping.BLL.ProductImgBean.SetProductImage(Convert.ToInt32(hidPrdt.Value), Convert.ToInt32(hidPrdtType.Value), FileUpload2);
            //GoShopping.BLL.ProductImgBean.SetProductImage(Convert.ToInt32(hidPrdt.Value), Convert.ToInt32(hidPrdtType.Value), FileUpload3);
            //GoShopping.BLL.ProductImgBean.SetProductImage(Convert.ToInt32(hidPrdt.Value), Convert.ToInt32(hidPrdtType.Value), FileUpload4);
            //GoShopping.BLL.ProductImgBean.SetProductImage(Convert.ToInt32(hidPrdt.Value), Convert.ToInt32(hidPrdtType.Value), FileUpload5);
            //GoShopping.BLL.ProductImgBean.SetProductImage(Convert.ToInt32(hidPrdt.Value), Convert.ToInt32(hidPrdtType.Value), FileUpload6);
            //GoShopping.BLL.ProductImgBean.SetProductImage(Convert.ToInt32(hidPrdt.Value), Convert.ToInt32(hidPrdtType.Value), FileUpload7);
            //GoShopping.BLL.ProductImgBean.SetProductImage(Convert.ToInt32(hidPrdt.Value), Convert.ToInt32(hidPrdtType.Value), FileUpload8);
            //GoShopping.BLL.ProductImgBean.SetProductImage(Convert.ToInt32(hidPrdt.Value), Convert.ToInt32(hidPrdtType.Value), FileUpload9);
            //GoShopping.BLL.ProductImgBean.SetProductImage(Convert.ToInt32(hidPrdt.Value), Convert.ToInt32(hidPrdtType.Value), FileUpload10);
            Response.Redirect("PrdtImageList.aspx?prdtId=" + hidPrdt.Value + "prdtTypeId" + hidPrdtType.Value);
        }
        protected void btnAddDetail_Click(object sender, EventArgs e)
        {
            string str = string.Empty;
            IList<Model.CustomDefine.ProductPropertyValueList> iPPVL = new List<Model.CustomDefine.ProductPropertyValueList>();
            Model.CustomDefine.ProductPropertyValueList ppvl = null;
            //按照类型属性值的个数来控制添加的次数.
            for (int i = 0; i < tbPrdtDetail.Rows.Count; i++)
            {
                //一行中有四个控件要循环访问
                for (int j = 0; j < 4; j++)
                {
                    //当为偶数行时,获取属性的键(从0开始的)
                    if (j % 2 == 0)
                    {
                        //如果此时控件的ID为"lbl2No",则表示从该控件开始已经无用,则跳出整个循环,否则添加到ppvl中.
                        if (this.tbPrdtDetail.Rows[i].Cells[j].Controls[0].ID == "lbl2No")
                        {
                            break;
                        }
                        ppvl = new GoShopping.Model.CustomDefine.ProductPropertyValueList();
                        ppvl.PropertyColumnName = ((Label)this.tbPrdtDetail.Rows[i].Cells[j].Controls[0]).ID;
                    }
                    else //当为奇数行时,获取属性的值(从0开始的),并添加到iPPVL中.
                    {
                        ppvl.PropertyValue = ((TextBox)this.tbPrdtDetail.Rows[i].Cells[j].Controls[0]).Text.Trim();
                        iPPVL.Add(ppvl);
                    }
                }
            }
            try
            {
                pb.AddOrUpdateProductDetailInfo(Convert.ToInt16(ddlType.SelectedValue), iPPVL);
                //ScriptManager.RegisterClientScriptBlock(UpdatePanel1, typeof(UpdatePanel), null, "<script>alert('添加成功!')</script>", false);
            }
            catch
            {
                //ScriptManager.RegisterClientScriptBlock(UpdatePanel1, typeof(UpdatePanel), null, "<script>alert('添加失败!')</script>", false);
            }
        }

        protected void btnAddBasic_Click(object sender, EventArgs e)
        {
            try
            {
                Model.Product prdt = GetBasicInfo();
                hidPrdtId.Value = pb.AddProductBase(prdt).ToString();
                if (FileUpload1.HasFile)
                {
                    BLL.ProductImgBean.SetProductImage(Convert.ToInt32(hidPrdtId.Value), prdt.ProductTypeID, FileUpload1);
                }
                hidPrdtId.Value = string.Empty;
                //ScriptManager.RegisterClientScriptBlock(UpdatePanel1, typeof(UpdatePanel), null, "<script>alert('添加成功!')</script>", false);
            }
            catch(Exception ex)
            {
                hidPrdtId.Value = string.Empty;
                //ScriptManager.RegisterClientScriptBlock(UpdatePanel1, typeof(UpdatePanel), null, "<script>alert('" + ex.Message + "!')</script>", false);
            }
        }

        protected void btnEditPrdtBasic_Click(object sender, EventArgs e)
        {
            try
            {
                Model.Product prdt = GetBasicInfo();
                pb.UpdateProductBaseInfo(prdt);
                if (FileUpload1.HasFile)
                {
                    BLL.ProductImgBean.SetProductImage(prdt.ID, prdt.ProductTypeID, FileUpload1);
                }
                UpdatePrdtConfig(prdt);
                //ScriptManager.RegisterClientScriptBlock(UpdatePanel1, typeof(UpdatePanel), null, "<script>alert('修改成功!')</script>", false);
            }
            catch
            {
                //ScriptManager.RegisterClientScriptBlock(UpdatePanel1, typeof(UpdatePanel), null, "<script>alert('修改失败!')</script>", false);
            }
        }

        private void UpdatePrdtConfig(GoShopping.Model.Product prdt)
        {
            List<ConfigNode> cnList = new List<ConfigNode>();
            ConfigNode cn = new ConfigNode();
            cn.Id = prdt.ID;
            cn.Name = prdt.Name;
            cn.Src = GetWebPath(GoShopping.BLL.ProductImgBean.GetProductImgPath(prdt.ID, prdt.ProductTypeID));
            cn.Price = Convert.ToDecimal(prdt.Price);
            cn.PriceMarket = Convert.ToDecimal(prdt.PriceMarket);
            cn.Description = prdt.BriefIntroduction;
            cnList.Add(cn);
            string xPath = "";
            try
            {
                GoShopping.Model.DiscountPrdct dp = new GoShopping.Model.DiscountPrdct();
                GoShopping.Model.RecomendPrdct rp = new GoShopping.Model.RecomendPrdct();
                if (new GoShopping.BLL.PrdctInfo.DiscountPrdctBean().IsPrdctHasDiscount(prdt.ID, DateTime.Now, out dp))
                {
                    xPath = "//Index/Promoted/pic[@Id='" + prdt.ID + "']";
                }
                else if (new GoShopping.BLL.PrdctInfo.RecomendPrdctBean().IsRecomendPrdct(prdt.ID, out rp))
                {
                    xPath = "//Index/Recommand/pic[@Id='" + prdt.ID + "']";
                }
                else
                {
                    return;
                }
                XMLManipulation.UpdateNodes(Server.MapPath("~/Config/PrdtConfig.xml"), xPath, cnList);
            }
            catch
            {
                throw;
            }
        }

        protected void btnEditPrdtDetail_Click(object sender, EventArgs e)
        {

        }

        protected void btnMorePics_Click(object sender, EventArgs e)
        {
            Response.Redirect("AddPrdtImages.aspx?prdtId=" + hidPrdtId.Value + "&prdtName=" + zlTxtPrdtName.Text.Trim() + "&prdtTypeId=" + ddlType.SelectedValue);
        }
        #endregion

        #region Dynamic Table
        /// <summary>
        /// 根据商品类型来动态生成类型属性
        /// </summary>
        /// <param name="ddl">商品类型下拉菜单控件</param>
        private void CreatePrdtDetailTable(DropDownList ddl)
        {
            BLL.ProductTypeBean ptb = new GoShopping.BLL.ProductTypeBean();
            if (ddl.SelectedIndex == -1)
            {
                return;
            }
            //根据选择的Value获得商品的类型属性表的所有字段
            IList<Model.CustomDefine.ProductTypeProperty> iPTList = ptb.GetProductTypeProperties(Convert.ToInt16(ddl.SelectedItem.Value));
            //根据选择的Value获得商品的类型属性字段的键值对
            IList<Model.CustomDefine.ProductPropertyValueList> iPPVL = ptb.GetProductTypePrptValue(Convert.ToInt16(ddl.SelectedItem.Value));
            //用来存储商品类型属性的中文属性名和属性类型
            string[] strText = new string[iPTList.Count];
            //用来存储商品类型属性的英文列名
            string[] strID = new string[iPTList.Count];
            int k = 0;//k,l只是做为循环计数用
            int l = 0;
            foreach (Model.CustomDefine.ProductTypeProperty ptp in iPTList)
            {
                strText[k] = ptp.PropertyName + ":" + ptp.ValueType;
                k++;
            }
            foreach (Model.CustomDefine.ProductPropertyValueList ppvl in iPPVL)
            {
                strID[l] = ppvl.PropertyColumnName;
                l++;
            }
            //Table一行有四列,第一列为strText的元素,第二列为要填写的值
            //三,四与一,二重复.根据商品属性类型的数量来计算添加的行数.
            //每行两个属性键值对,所以Mode 2取余来取得行数
            int counts = iPTList.Count / 2 + iPTList.Count % 2;//添加四个控件
            int m = 0;//m,n来控制类型属性的个数
            int n = 0;
            //i用来控制行计数,从1开始表示第一行,当>行个数时退出
            for (int i = 1; i <= counts; i++)
            {
                //当m大于等于类型属性个数时或者n大于等于类型属性的键值对个数时,退出循环.
                if (m >= iPTList.Count || n >= iPPVL.Count)
                {
                    break;
                }
                TableRow row = new TableRow();
                TableCell cell1 = new TableCell();
                TableCell cell2 = new TableCell();
                TableCell cell3 = new TableCell();
                TableCell cell4 = new TableCell();
                Label lbl1 = new Label();
                Label lbl2 = new Label();
                TextBox text1 = new TextBox();
                TextBox text2 = new TextBox();

                lbl1.ID = strID[n++];
                lbl1.Text = strText[m++];
                text1.ID = "txt1" + i.ToString();
                //如果计算的行个数等于1,也就是说至少会有一个类型属性键值对
                //此时进行判断,如果有后续类型属性时,也就是m或者n自增后的值
                //小于类型属性个数时,(因为m,n从0开始计数,如果等于或者大于Count
                //则表示已没有后续类型属性).继续设置第二个键值对,也就是一行
                //中的后两个控件.否则没有后续类型属性,则把这两个控件的ID设置为
                //固定的值,以在后面添加或者修改时容易分析取出.
                if (m < iPTList.Count || n < iPPVL.Count)
                {
                    lbl2.ID = strID[n++];
                    lbl2.Text = strText[m++];
                    text2.ID = "txt2" + i.ToString();
                }
                else
                {
                    lbl2.ID = "lbl2No";
                    text2.ID = "txt2No";
                    lbl2.Visible = false;
                    text2.Visible = false;
                }

                cell1.Controls.Add(lbl1);
                cell2.Controls.Add(text1);
                cell3.Controls.Add(lbl2);
                cell4.Controls.Add(text2);
                #region Table Style Set
                cell1.HorizontalAlign = HorizontalAlign.Left;
                cell1.Width = 100;

                cell2.HorizontalAlign = HorizontalAlign.Left;
                cell2.Width = 200;

                cell3.Width = 100;
                cell3.HorizontalAlign = HorizontalAlign.Left;

                cell4.Width = 400;
                cell4.HorizontalAlign = HorizontalAlign.Left;

                #endregion
                row.Cells.Add(cell1);
                row.Cells.Add(cell2);
                row.Cells.Add(cell3);
                row.Cells.Add(cell4);

                this.tbPrdtDetail.Rows.Add(row);
            }
        }
        #endregion

        #region common methods
        private void BindProductInfo(string p)
        {
            Model.Product prdt = pb.GetProduct(Convert.ToInt16(p));
            hidPrdtId.Value = p;
            lblInPrice.Text = new BLL.PrdctInfo.StockProductBean().FindLastestInPrice(Convert.ToInt32(p)).ToString();
            zlTxtPrdtName.Text = prdt.Name;
            zlTxtCount.Text = prdt.Count.ToString();
            if (prdt.IsShowOnsale.Value)
            {
                rdbtnYes.Checked = true;
            }
            else
            {
                rdbtnNo.Checked = true;
            }
            txtPCode.Text = prdt.PCode;
            txtAccessory.Text = prdt.Accessory;
            FreeTextBox2.Text = prdt.BriefIntroduction;
            txtSaledPrice.Text = prdt.Price.ToString();
            txtMarketPrice.Text = prdt.PriceMarket.ToString();

            SetDDLType(prdt.ProductTypeID.ToString());
            SetDDLTag(prdt.Tag);
            SetDDLBrand(prdt.Brand);
            SetDDLSupplier(prdt.SupplyerID);
        }

        private Model.Product GetBasicInfo()
        {
            Model.Product prdt = new GoShopping.Model.Product();
            if (string.IsNullOrEmpty(zlTxtPrdtName.Text.Trim()))
            {
                return null;
            }
            if (!string.IsNullOrEmpty(hidPrdtId.Value))
            {
                prdt.ID = Convert.ToInt32(hidPrdtId.Value);
            }
            prdt.Name = zlTxtPrdtName.Text.Trim();
            prdt.Tag = ddlTag.SelectedItem.Text;
            prdt.Count = Convert.ToInt32(zlTxtCount.Text.Trim());
            prdt.IsShowOnsale = rdbtnYes.Checked ? true : false;
            prdt.Brand = ddlBrand.SelectedItem.Text;
            prdt.ProductTypeID = Convert.ToInt16(ddlType.SelectedItem.Value);
            prdt.PCode = txtPCode.Text.Trim();
            prdt.SupplyerID = Convert.ToInt32(ddlSupplier.SelectedItem.Value);
            prdt.Accessory = txtAccessory.Text.Trim();
            prdt.BriefIntroduction = FreeTextBox2.Text.Trim();
            prdt.Price = Convert.ToDecimal(txtSaledPrice.Text.Trim());
            prdt.PriceMarket = Convert.ToDecimal(txtMarketPrice.Text.Trim());
            return prdt;
        }
        #endregion
}
}

//private void CreatePrdtDetailTable(DropDownList ddl)
//{
//    BLL.ProductTypeBean ptb = new GoShopping.BLL.ProductTypeBean();
//    IList<Model.CustomDefine.ProductTypeProperty> iPTList = ptb.GetProductTypeProperties(Convert.ToInt16(ddl.SelectedItem.Value));

//    string[] str = new string[iPTList.Count];
//    int k = 0;
//    foreach (Model.CustomDefine.ProductTypeProperty ptp in iPTList)
//    {
//        str[k] = ptp.PropertyName + ":" + ptp.ValueType;
//        k++;
//    }

//    int counts = iPTList.Count / 2 + iPTList.Count % 2;//假设添加四个控件
//    int m = 0;
//    for (int i = 1; i <= counts; i++)
//    {
//        if (m >= iPTList.Count)
//        {
//            break;
//        }
//        TableRow row = new TableRow();
//        TableCell cell1 = new TableCell();
//        TableCell cell2 = new TableCell();
//        TableCell cell3 = new TableCell();
//        TableCell cell4 = new TableCell();
//        Label lbl1 = new Label();
//        Label lbl2 = new Label();
//        TextBox text1 = new TextBox();
//        TextBox text2 = new TextBox();

//        lbl1.ID = "lbl1" + i.ToString();
//        lbl2.ID = "lbl2" + i.ToString();
//        lbl1.Text = str[m++];
//        if (m < iPTList.Count)
//        {
//            lbl2.Text = str[m++];
//        }
//        else
//        {
//            lbl2.Visible = false;
//            text2.Visible = false;
//        }
//        text1.ID = "txt1" + i.ToString();
//        text2.ID = "txt2" + i.ToString();

//        cell1.Controls.Add(lbl1);
//        cell2.Controls.Add(text1);
//        cell3.Controls.Add(lbl2);
//        cell4.Controls.Add(text2);

//        row.Cells.Add(cell1);
//        row.Cells.Add(cell2);
//        row.Cells.Add(cell3);
//        row.Cells.Add(cell4);

//        this.tbPrdtDetail.Rows.Add(row);
//    }
//}